package com.sbox;

import com.sbox.db.ContentMgr;
import com.sbox.model.FilterPeriod;
import com.sbox.model.NoteItem;
import com.sbox.model.SBoxConfig;
import com.sbox.model.SBoxConst;
import com.sbox.util.SBoxLog;
import com.sbox.util.Utils;
import com.sbox.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

public class NotesActivity extends Activity implements TextWatcher{
	private EditText mEditSearch = null;
	private ImageView mBtnFilter = null;
	private NoteAdapter mAdapter = null;
	private ListView mListNotes = null;
	private TitleBar mTitleBar = null;
	private SBoxConfig mConfig = null;
	private boolean mPassVerified = false;
	private boolean mPassValid = true;
	private int mNoteIndex = 0;
	private String mFilter = null;
	private int mFilterPeriod = FilterPeriod.PERIOD_ALL;
	
	private View.OnClickListener mAddListener = new View.OnClickListener() {		
		@Override
		public void onClick(View v) {
			gotoNoteView();
		}
	};	
	
	/*
	private View.OnClickListener mBtnFilterListener = new View.OnClickListener() {		
		@Override
		public void onClick(View v) {			
			AlertDialog.Builder dialog = new AlertDialog.Builder(NotesActivity.this);
			dialog.setTitle(R.string.str_notes_choose_date);
			dialog.setSingleChoiceItems(R.array.note_show_period, -1, mFilterConfirmListener);
			//dialog.setPositiveButton(R.string.str_yes, null);
			//dialog.setNegativeButton(R.string.str_cancel, null);
			dialog.show();
		}
	};
	
	private DialogInterface.OnClickListener mFilterConfirmListener = new DialogInterface.OnClickListener() {		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch( which )
			{
			case 0:
				mFilterPeriod = FilterPeriod.PERIOD_1MONTH;
				break;
			case 1:
				mFilterPeriod = FilterPeriod.PERIOD_3MONTH;
				break;
			case 2:
				mFilterPeriod = FilterPeriod.PERIOD_1YEAR;
				break;
			case 3:
				mFilterPeriod = FilterPeriod.PERIOD_ALL;
				break;
			}
			dialog.dismiss();	
			
			NotesActivity.this.refreshNotes();
		}
	};
	*/
	
	private AdapterView.OnItemClickListener mNoteItemClickListner = new AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			if( parent == null || view == null || position < 0 || id < 0 )
			{
				SBoxLog.info("NotesActivity.onItemClick, invalid parameters.");
				return;
			}
			
			NoteItem note = (NoteItem)mAdapter.getItem(position);						
			if( note != null )
			{
				mNoteIndex = position;
				gotoNoteView(note.ID);
			}
			else
			{
				SBoxLog.error("NotesActivity.onItemClick, note=null");
				return;
			}			
		}
	};
	
	private DialogInterface.OnClickListener mClearListener = new DialogInterface.OnClickListener() 
	{		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			if( which == DialogInterface.BUTTON_POSITIVE )
			{
				ContentMgr.getInstance(NotesActivity.this).deleteAllNotes();
				refreshNotes();
			}
			else
			{
			}
		}
	};	
	
	@Override
	public void onCreate(Bundle savedBundle)
	{
		super.onCreate(savedBundle);
		setContentView(R.layout.notes_view);
		
		mEditSearch = (EditText)findViewById(R.id.notes_search);		
		mEditSearch.addTextChangedListener(this);
		
		mListNotes = (ListView)findViewById(R.id.list_notes);		
		mListNotes.setOnItemClickListener(mNoteItemClickListner);
		
		mTitleBar = (TitleBar)findViewById(R.id.notes_title);
		mTitleBar.getButton1().setVisibility(View.INVISIBLE);
		mTitleBar.getButton2().setOnClickListener(mAddListener);
	}
	
	@Override
	public void onResume()
	{
		super.onResume();	
		
		SBoxLog.info("onResume");
		
		mConfig = SBoxConfig.getInstance(this);
		mConfig.loadConfig();
		
		/* setting password when login for the firs time?
		if( mConfig.mFirstTime )
		{
			gotoSettingView();
		}
		*/
		
		if( mConfig.mNeedPassword )
		{
			if( !mPassVerified )
				gotoLoginView();
			else
			{
				if( mPassValid )
					refreshNotes();
			}
		}
		else
			refreshNotes();
		
		updateTitle();
	}
	
	@Override
	public void onActivityResult(int code, int result, Intent i)
	{
		SBoxLog.info("onActivityResult, code=" + code);
		
		if( code == SBoxConst.REQUST_LOGIN ) {
			if( result == SBoxConst.REQUEST_LOGIN_OK )
			{
				mPassVerified = true;
				mPassValid = true;
			}
			else if( result == SBoxConst.REQUEST_LOGIN_FAIL)
			{
				mPassVerified = true;
				mPassValid = false;
			}
		}
		else if( code == SBoxConst.REQUST_NOTE ) {
			if( result == SBoxConst.REQUEST_NOTE_NEXT )
			{
				NoteItem note = null;
				
				if( mNoteIndex >= mAdapter.getCount() )
					return;				
				mNoteIndex++;				
				note = (NoteItem)mAdapter.getItem(mNoteIndex);				
				if( note != null ) {					
					gotoNoteView(note.ID);
				}
			}
			else if( result == SBoxConst.REQUEST_NOTE_PREV ) {
				NoteItem note = null;
				
				if( mNoteIndex == 0 )
					return;				
				mNoteIndex--;				
				note = (NoteItem)mAdapter.getItem(mNoteIndex);				
				if( note != null ) {					
					gotoNoteView(note.ID);
				}
			}
		}				
	}
	
	@Override 
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = this.getMenuInflater();
		
		inflater.inflate(R.menu.main_menu, menu);
		
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		switch( item.getItemId() )
		{
		case R.id.menu_password:
			gotoPasswordView();
			break;
		case R.id.menu_backup:	
			gotoBackupView();
			break;
		case R.id.menu_clear:
			deleteAllNotes();
			break;
		case R.id.menu_about:
			gotoAboutView();
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
				
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count)
	{
		mFilter = s.toString();		
			
		refreshNotes();
	}

	@Override
	public void afterTextChanged(Editable s) {
				
	}
	
	private void refreshNotes()
	{
		mAdapter = new NoteAdapter(this);
		mAdapter.add( ContentMgr.getInstance(this).loadNoteTitles());	
		mAdapter.filter(mFilter, mFilterPeriod);
		
		mListNotes.setVisibility(View.GONE);
		mListNotes.setAdapter(mAdapter);
		mListNotes.setVisibility(View.VISIBLE);
	}
	
	private void updateTitle()
	{	
		int count = 0;
		String title = null;
		
		if( mAdapter == null )
			return;
		
		count = mAdapter.getCount();
		if( count != 0 )
		{
			title = this.getText(R.string.str_app).toString();
			title += "(" + count + ")";
			mTitleBar.getText().setText(title);
		}
	}
	
	private void gotoNoteView()
	{
		Intent i = new Intent(this, NoteActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
		startActivityForResult(i, SBoxConst.REQUST_NOTE);
	}
	
	private void gotoNoteView(long id)
	{	
		Intent i = new Intent(NotesActivity.this, NoteActivity.class);
		i.putExtra(SBoxConst.KEY_NOTE_ID, id);
		i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
		startActivityForResult(i, SBoxConst.REQUST_NOTE);
	}
	
	private void gotoLoginView()
	{
		Intent i = new Intent(this, LoginActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
		this.startActivityForResult(i, SBoxConst.REQUST_LOGIN);
	}
	
	private void gotoPasswordView()
	{
		Intent i = new Intent(this, PasswordActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
		this.startActivityForResult(i, SBoxConst.REQUST_PASSWORD);
	}
	
	private void gotoAboutView()
	{
		Intent i = new Intent(this, AboutActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
		this.startActivityForResult(i, SBoxConst.REQUST_ABOUT);
	}
	
	private void gotoBackupView()
	{
		Intent i = new Intent(this, BackupActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
		this.startActivityForResult(i, SBoxConst.REQUST_BACKUP);
	}
	
	private void deleteAllNotes()
	{		
		Dialog dialog = new AlertDialog.Builder(this).setMessage(R.string.str_confirm_clear).setPositiveButton(R.string.str_yes, mClearListener).setNegativeButton(R.string.str_cancel, mClearListener).create();				
		dialog.show();
	}

}
